package com.jumi.microservice.common.base;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.HttpStatus;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.page.PageDomain;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.page.TableSupport;
import com.jumi.microservice.common.utils.DateProvider;
import com.jumi.microservice.common.utils.StringProvider;
import com.jumi.microservice.common.utils.sql.SqlUtils;
import com.jumi.microservice.jwt.constant.JwtAdminInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author Dirk
 * @Date 2020-07-08 10:51
 */
public abstract class BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest req, HttpServletResponse res) {
        this.request = req;
        this.response = res;
    }

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateProvider.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringProvider.isNotNull(pageNum) && StringProvider.isNotNull(pageSize)) {
            String orderBy = SqlUtils.escapeOrderBySql(pageDomain.combineOrderRule());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMessage("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    protected <T> ResponseResult<T> success(T data) {
        return ResponseResult.success(data);
    }

    /**
     * 获取登录用户的UID
     */
    protected Long getUid() {
        long uid = 0;
        // TODO 获取用户信息
        if (!StringUtils.isBlank(request.getHeader(RequestConstant.ADMIN_ID))) {
            uid = Long.parseLong(request.getHeader(RequestConstant.ADMIN_ID));
        }
        return uid;
    }

    /**
     * 获取登录用户的名字
     */
    protected String getUserName() {
        String userName = null;
        // TODO 获取用户信息
        if (!StringUtils.isBlank(request.getHeader(RequestConstant.ADMIN_NAME))) {
            userName = request.getHeader(RequestConstant.ADMIN_NAME);
        }
        return userName;
    }

    /**
     * 获得 C端登录人用户id
     * @return
     */
    protected Integer getApiUserId(){
        int intHeader = request.getIntHeader(JwtAdminInfo.apiUserId);
        return intHeader<0?0:intHeader;
    }

    /**
     * 获得C端登录人昵称
     */
    protected String getApiUserName(){
        String header = request.getHeader(JwtAdminInfo.apiName);
        try {
            return URLDecoder.decode(StrUtil.isEmpty(header)?"":header,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return header;
    }


    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ResponseResult toResponse(int rows) {
        return rows > 0 ? ResponseResult.success() : ResponseResult.error();
    }

}
